package ocr

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

// ocr引擎接口
type IEngine interface {
	IRouteBaseCompose
	Listen(port int) error
}

// 基于gin的封装
type OcrEngine struct {
	ocrEngine *gin.Engine //引擎
	Port      int         //监听端口
}

// // 创建引擎下的分组
func (o *OcrEngine) Group(path string) IRouteGroup {
	return &OcrGroup{
		ocrGroup: o.ocrEngine.Group(path),
	}
}

// 使用中间件
func (o *OcrEngine) Use(handles ...OcrHandler) {
	for _, handle := range handles {
		o.ocrEngine.Use(handle.createOcrHandle(o.ocrEngine.BasePath()))
	}
}

// 监听
func (o *OcrEngine) Listen(port int) error {
	if port > 0 {
		o.Port = port
	}
	err := o.ocrEngine.Run(fmt.Sprintf(":%d", o.Port))
	if err != nil {
		return err
	}
	fmt.Println("ocr服务器运行端口:", o.Port)
	return nil
}

// GET
func (o *OcrEngine) GET(path string, handlers ...OcrMiddle) {
	list := make([]gin.HandlerFunc, 0)
	for _, v := range handlers {
		list = append(list, func(ctx *gin.Context) {
			v(ctx)
		})
	}
	o.ocrEngine.GET(path, list...)
}

// POST
func (o *OcrEngine) POST(path string, handlers ...OcrMiddle) {
	list := make([]gin.HandlerFunc, 0)
	for _, v := range handlers {
		list = append(list, func(ctx *gin.Context) {
			v(ctx)
		})
	}
	o.ocrEngine.POST(path, list...)
}

// PUT
func (o *OcrEngine) PUT(path string, handlers ...OcrMiddle) {
	list := make([]gin.HandlerFunc, 0)
	for _, v := range handlers {
		list = append(list, func(ctx *gin.Context) {
			v(ctx)
		})
	}
	o.ocrEngine.PUT(path, list...)
}

// DELETE
func (o *OcrEngine) DELETE(path string, handlers ...OcrMiddle) {
	list := make([]gin.HandlerFunc, 0)
	for _, v := range handlers {
		list = append(list, func(ctx *gin.Context) {
			v(ctx)
		})
	}
	o.ocrEngine.DELETE(path, list...)
}

// 创建ocr路由对象
func Create(opts ...gin.OptionFunc) IEngine {
	r := gin.New(opts...)
	return &OcrEngine{
		ocrEngine: r,
	}
}
